package com.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.domain.User;
import com.core.domain.UserRoles;
import com.core.dto.UserInfoDto;
import com.core.mapper.UserRolesMapper;
import com.core.mapper.UsersMapper;
import com.core.resp.AjaxResponse;
import com.core.resp.PageResult;
import com.core.vo.UserRolesVo;
import com.core.vo.UserVo;
import com.core.service.UsersService;
import com.core.utils.IdGeneratorSnowFlake;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.Arrays;
import java.util.List;

/**
 * @author legion
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2025-05-31 22:41:52
 */
@Slf4j
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User>
        implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public User selectByUsername(String username) {
        return query().eq("username", username).one();
    }

    @Override
    public UserInfoDto selectInfoByUser(String username) {
        UserInfoDto userInfoDto = usersMapper.getByUsername(username);
        if (userInfoDto != null && userInfoDto.getPermissions() != null) {
            userInfoDto.setRolesPermissions(userInfoDto.getPermissions().split(","));
        }
        return userInfoDto;
    }

    @Override
    public PageResult<UserInfoDto> getUserListPage(User user, Long pageSize, Long pageNum) {
        Long indexStart = (pageNum - 1) * pageSize;
        List<UserInfoDto> listPage = usersMapper.getListPage(user, pageSize, indexStart);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (user != null && !StringUtil.isNullOrEmpty(user.getUsername())) {
            queryWrapper.eq(User::getUsername, user.getUsername());
        }
        if (user != null && !StringUtil.isNullOrEmpty(user.getEmail())) {
            queryWrapper.eq(User::getEmail, user.getEmail());
        }
        Long total = usersMapper.selectCount(queryWrapper);
        return new PageResult<>(pageSize, pageNum, listPage, total);
    }

    @Transient
    @Override
    public AjaxResponse addUser(UserVo userVo) {
        try {
            User user = new User();
            BeanUtils.copyProperties(userVo, user);
            String encode = passwordEncoder.encode(user.getPassword());
            user.setPassword(encode);
            long id = IdGeneratorSnowFlake.snowFlakeId();
            user.setId(id);
            List<Long> roles = userVo.getRoles();

            usersMapper.insert(user);
            userRolesMapper.addBatch(id, roles);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException();

        }
        return AjaxResponse.success(200, "添加成功", null);
    }

    @Transactional
    @Override
    public AjaxResponse updateRoles(Long userId, UserRolesVo userRolesVo) {
        if (userRolesVo == null && StringUtil.isNullOrEmpty(userRolesVo.getRoles())) {
            return AjaxResponse.error(405, "修改失败，信息不完整");
        }
        try {
            String[] temp = userRolesVo.getRoles().split(",");
            List<String> roles = Arrays.asList(temp);
            log.info("修改的角色：{}", roles);
            LambdaQueryWrapper<UserRoles> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRoles::getUserId, userId);
            queryWrapper.notIn(UserRoles::getRoleId, roles);
            userRolesMapper.delete(queryWrapper);
            userRolesMapper.updateRoles(userId, roles);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return AjaxResponse.success(200, "修改成功", null);
    }

    @Transactional
    @Override
    public void deleteUser(List<Long> userIds) {
        usersMapper.deleteBatchByIds(userIds);
        userRolesMapper.deleteBatchByIds(userIds);
    }
}




